<?php

namespace App\Http\Middleware;

use Closure;
use Green\Request\V20180509\TextScanRequest;
use Illuminate\Support\Facades\Log;

class WordFilteringMiddleware
{
    private $client;
    private $request;
    CONST SCENES = ['antispam'];
    
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request)
    {
        //Log::debug($request->all());
        $this->init();

        $setContent = [];
        $setContentDataList = [];
        $questionData = [];

        foreach ($request as $key => $value) {
            $setContentDataList[$key]["data"] = $value;
            $dataId = $this->getDataId();

            $setContentDataList[$key]['dataId'] = $dataId;
            if (isset($value['c_content']) && $value['c_content'] && !empty($value['c_content'])) {
                $c_content = json_decode($value['c_content'], true);
                if ($c_content && is_array($c_content)) {
                    $c_mess_contents = array_column($c_content, "mess");
                    if (is_array($c_mess_contents)) {
                        $value['c_content'] = @implode("  ",  $c_mess_contents);
                        $value['c_content'] = str_replace("啦，沙", "", $value['c_content']);
                    }
                }
            }
            $setContent[] = ['dataId' => $dataId, 'content' => implode("  ",  array_values($value))];
        }

        if ($setContent) {
            $checkResult = $this->checkContent($setContent);
            Log::debug($checkResult);
            if ($checkResult) {
                foreach ($setContentDataList as $key => $value) {
                    $dataId = $value['dataId'];
                    $find = array_values(array_filter($checkResult, function ($param) use ($dataId) {
                        return $param->dataId == $dataId;
                    }));
                    if ($find && $find[0]->code == 200 && $find[0]->results && $find[0]->results[0] && $find[0]->results[0]->suggestion == 'pass') {

                    } else {
                        $questionData[$key]['handle'] = $value;
                        $questionData[$key]['results'] = $find[0];
                    }
                }
            }
        }

        if ($questionData) {
            $questionData = array_values($questionData);
        }

        return $questionData;

//
//        $setContentDataIdList = [];
//        foreach ($request as $key => $value) {
//            $setContentDataIdList[$key]["data"] = $value;
//
//            if (isset($request[$key]['name']) && !empty($request[$key]['name'])) {
//                $content = $request[$key]['name'];
//                $dataId = $setContentDataIdList[$key]['id'][] = $this->getDataId();
//                $setContentDataIdList[$key]['keys'][] = "name";
//                $setContent[] = ['dataId' => $dataId, 'content' => $content];
//            }
//            if (isset($request[$key]['notice']) && !empty($request[$key]['notice'])) {
//                $content = $request[$key]['notice'];
//                $dataId = $setContentDataIdList[$key]['id'][] = $this->getDataId();
//                $setContentDataIdList[$key]['keys'][] = "notice";
//                $setContent[] = ['dataId' => $dataId, 'content' => $content];
//            }
//
//            if (isset($request[$key]['desc']) && !empty($request[$key]['desc'])) {
//                $content = $request[$key]['desc'];
//                $dataId = $setContentDataIdList[$key]['id'][] = $this->getDataId();
//                $setContentDataIdList[$key]['keys'][] = "desc";
//                $setContent[] = ['dataId' => $dataId, 'content' => $content];
//            }
//
//            if (isset($request[$key]['nickname']) && !empty($request[$key]['nickname'])) {
//                $content = $request[$key]['nickname'];
//                $dataId = $setContentDataIdList[$key]['id'][] = $this->getDataId();
//                $setContentDataIdList[$key]['keys'][] = "nickname";
//                $setContent[] = ['dataId' => $dataId, 'content' => $content];
//            }
//
//            if (isset($request[$key]['sign']) && !empty($request[$key]['sign'])) {
//                $content = $request[$key]['sign'];
//                $dataId = $setContentDataIdList[$key]['id'][] = $this->getDataId();
//                $setContentDataIdList[$key]['keys'][] = "sign";
//                $setContent[] = ['dataId' => $dataId, 'content' => $content];
//            }
//
//            if (isset($request[$key]['school']) && !empty($request[$key]['school'])) {
//                $content = $request[$key]['school'];
//                $dataId = $setContentDataIdList[$key]['id'][] = $this->getDataId();
//                $setContentDataIdList[$key]['keys'][] = "school";
//                $setContent[] = ['dataId' => $dataId, 'content' => $content];
//            }
//        }
//
//        if ($setContent) {
//            $checkResult = $this->checkContent($setContent);
//            if ($checkResult) {
//                foreach ($setContentDataIdList as $key => $value) {
//                    if (isset($value['id']) && $value['id']) {
//                        foreach ($value['id'] as $ikey => $ivalue) {
//                            $find = array_values(array_filter($checkResult, function ($param) use ($ivalue) {
//                                return $param->dataId == $ivalue;
//                            }));
//
//                            if ($find && $find[0]->code == 200 && $find[0]->results && $find[0]->results[0] && $find[0]->results[0]->suggestion == 'pass') {
//
//                            } else {
//                                $questionData[$key]['handle'] = $value;
//                                $questionData[$key]['results'][$ikey][] = $find[0];
//                                $questionData[$key]['keys'][$ikey][] = $value['keys'][$ikey];
//                            }
//                        }
//                    }
//
//                    if (isset($questionData[$key])) {
//                        $questionData[$key]['results'] = array_values($questionData[$key]['results']);
//                    }
//                }
//            }
//        }
//        if ($questionData) {
//            $questionData = array_values($questionData);
//        }
//
//        var_dump($questionData);exit;``
//        return $questionData;


//        return $next($request);
    }
    
    private function init()
    {
        $iClientProfile = \DefaultProfile::getProfile("cn-beijing", config("oss.accesskeyid"), config("oss.accesskeysecret"));
        \DefaultProfile::addEndpoint('cn-beijing', 'cn-beijing', 'Green', "green.cn-beijing.aliyuncs.com");
        $this->client = new \DefaultAcsClient($iClientProfile);
        $this->request = new TextScanRequest();
    }
    
    
    private function setContent($tasks = [])
    {
        $tasks = json_encode(['tasks' => $tasks, 'scenes' => self::SCENES]);
        $this->request->setMethod('POST');
        $this->request->setAcceptFormat('JSON');
        $this->request->setContent($tasks);
    }
    
    private function checkContent($tasks)
    {
        $this->request->setMethod('POST');
        $this->request->setAcceptFormat('JSON');
        $this->request->setContent($tasks);
        /**
         * 文本垃圾检测： antispam
         **/
        $this->request->setContent(json_encode(array("tasks" => $tasks,
            "scenes" => array("antispam"), "bizType" => "kkaudio")));
        try {
            $response = $this->client->getAcsResponse($this->request);
            if(200 == $response->code){
                $taskResults = $response->data;
                return $taskResults;
//                foreach ($taskResults as $taskResult) {
//                    if(200 == $taskResult->code){
//                        $sceneResults = $taskResult->results;
//                        echo json_encode($sceneResults);exit;
//                        foreach ($sceneResults as $sceneResult) {
//                            $scene = $sceneResult->scene;
//                            $suggestion = $sceneResult->suggestion;
//                            //根据scene和suggetion做相关处理
//                            //do something
//                        }
//                        return $sceneResults;
//                    }else{
//                        print_r("task process fail:" + $response->code);
//                    }
//                }
            }else{
                print_r("detect not success. code:" + $response->code);
            }
        } catch (Exception $e) {
            print_r($e);
        }
    }
    
    private function getDataId()
    {
        return uniqid();
    }
}
